<?php

namespace app\site\service\site;

use app\common\exception\MiException;
use app\model\sys\UploadFile;
use app\site\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;

class UploadFileService extends \app\site\service\SiteBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new UploadFile();
    }

    /**
     * @inheritDoc
     */
    function formatData(array $data): array
    {
        return $data;
    }

    public function query(): Query
    {
        return $this->makeQuery()->filter(function ($v) {
            $fileType = 'file';
            $mime = $v->file_mime;
            if (str_contains($mime, 'image/')){
                $fileType = 'image';
            }elseif (str_contains($mime,'video/')){
                $fileType = 'video';
            }
            $v->fileType = $fileType;
        });
    }

    /***
     * 重写delete
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete()
    {
        Db::transaction(function () {
            $list = $this->query()->lock(true)->select();
            $this->query()->delete();
            foreach ($list as $v){
                // 删除对应文件
                $realpath = root_path() . $v->save_type. $v->path;
                if (is_file($realpath)){
                    unlink($realpath);
                }
            }
        });
    }
}
